﻿using SqlSugar;

namespace D.UtilSqlsugarOrm
{
    /// <summary>
    /// SqlSugar 事务和工作单元
    /// </summary>
    public sealed class SqlSugarUnitOfWork : ISqlsugarUnitOfWork
    {
        /// <summary>
        /// SqlSugar委托
        /// </summary>
        private readonly ISqlSugarClient _sqlSugarClient;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarClient">SqlSugar委托</param>

        public SqlSugarUnitOfWork(ISqlSugarClient sqlSugarClient)
        {
            Console.WriteLine($"初始化事务工作单元:{sqlSugarClient.ContextID}");
            this._sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public void BeginTransaction()
        {
            try
            {
                Console.WriteLine($"开启事务：{_sqlSugarClient.ContextID}");
                _sqlSugarClient.Ado.BeginTran();
            }
            catch (Exception ex)
            {
                throw new Exception("开启事务出错",ex);
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTransaction()
        {
            try
            {
                Console.WriteLine($"提交事务：{_sqlSugarClient.ContextID}");
                _sqlSugarClient.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                throw new Exception("提交事务出错",ex);
            }
        }

        /// <summary>
        /// 释放连接
        /// </summary>
        public void OnDispose()
        {
            Console.WriteLine($"释放连接：{_sqlSugarClient.ContextID}");
            _sqlSugarClient.Dispose();
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollbackTransaction()
        {
            try
            {
                Console.WriteLine($"回滚事务：{_sqlSugarClient.ContextID}");
                _sqlSugarClient.Ado.RollbackTran();
            }
            catch (Exception ex)
            {

                throw new Exception("回滚事务时出错", ex);
            }
        }
    }
}